﻿package com.google.zxing.client.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.webkit.WebView;
import android.widget.Toast;

public class WebSearch {

	private Activity activity = null;
	
	
	public WebSearch() {
	}

        /**
         * 设置需调用该WebSearch的activity
         * @param activity
         */
	public void setActivity(Activity activity) {
		this.activity = activity;
	}
	
        /**
         * 创建内嵌浏览器
         */
	private WebView createWebView() {
		WebView browser = new WebView(activity);
		browser.getSettings().setJavaScriptEnabled(true);
		browser.requestFocus();
		browser.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		return browser;
	}

        /**
         * 调用浏览器的intent，并打开浏览器
         */
	private void launchIntent(Intent intent) {
		if (intent != null) {
			//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			try {
				activity.startActivity(intent);
			} catch (ActivityNotFoundException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				builder.setTitle(R.string.app_name);
				builder.setMessage(R.string.msg_intent_failed);
				builder.setPositiveButton(R.string.button_ok, null);
				builder.show();
			}
		}
	}

        /**
         * 创建浏览器的intent，设置浏览的链接
         */
	public void webSearch(String query) {
		Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
		intent.putExtra(SearchManager.QUERY, query);
		launchIntent(intent);
	}
	
        /**
         * 外部调用的入口
         */
	public void to(String code) {
		
		String url = activity.getResources().getString(R.string.url_web_search);
		Uri uri = Uri.parse(url + code);
		
	
		// 跳转 
		
		// 调用浏览器方式
		Intent intent  = new Intent(Intent.ACTION_VIEW, uri);
		launchIntent(intent);
		
		// 内嵌浏览器方式  目前这种方式有点问题
		//WebView browser = createWebView();
		//browser.loadUrl(uri.toString());
	}



}
